package cn.wolfcode.business.service.impl;

import cn.wolfcode.business.domain.BusAppointment;
import cn.wolfcode.business.domain.BusStatement;
import cn.wolfcode.business.mapper.BusStatementMapper;
import cn.wolfcode.business.service.IBusAppointmentService;
import cn.wolfcode.business.service.IBusStatementService;
import cn.wolfcode.business.util.DateUtil;
import cn.wolfcode.business.util.RegexUtils;
import cn.wolfcode.business.util.VehiclePlateNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 结算单Service业务层处理
 * 
 * @author wolfcode
 * @date 2025-09-20
 */
@Service
public class BusStatementServiceImpl implements IBusStatementService 
{
    @Autowired
    public BusStatementMapper busStatementMapper;
    @Autowired
    private IBusAppointmentService appointmentService;
    @Override
    public List<BusStatement> selectBusStatementList(BusStatement busStatement) {
        return busStatementMapper.selectBusStatementList(busStatement);
    }

    @Override
    public BusStatement selectBusStatementById(Long id) {
        return busStatementMapper.selectBusStatementById(id);
    }

    @Override
    public int insertBusStatement(BusStatement busStatement) {
        if (busStatement==null) {
            throw new RuntimeException("参数异常");
        }
        if (busStatement.getCustomerName()==null
                || busStatement.getLicensePlate()==null
                || busStatement.getActualArrivalTime()==null
                || busStatement.getServiceType()==null
                || busStatement.getCarSeries()==null
                || busStatement.getCustomerPhone()==null) {
            throw new RuntimeException("参数异常");
        }
        if (!RegexUtils.isPhoneLegal(busStatement.getCustomerPhone())) {
            throw new RuntimeException("手机号格式不正确");
        }
        if (VehiclePlateNoUtil.getVehiclePlateNo(busStatement.getLicensePlate())==null) {
            throw new RuntimeException("车牌号格式不正确");
        }
        Date updateNow = DateUtil.changeDate(new Date(), Calendar.MINUTE, 1);
        if (updateNow.before(busStatement.getActualArrivalTime())) {
            throw new RuntimeException("到店时间需要早于当前时间");
        }
        busStatement.setStatus(BusStatement.STATUS_CONSUME);
        busStatement.setIsDelete(BusStatement.IS_NOT_DELETE);
        busStatement.setCreateTime(new Date());
        return busStatementMapper.insertBusStatement(busStatement);
    }
//    @Override
//    public int general(BusAppointment busAppointment) {
//        if (busAppointment==null) {
//            throw new RuntimeException("参数异常");
//        }
//        BusStatement busStatement = new BusStatement();
//        // 查询所有结算单
//        List<BusStatement> allStatements = busStatementMapper.selectBusStatementList(busStatement);
//        // 检查是否已存在相同预约ID的结算单
//        for (BusStatement statement : allStatements) {
//            if (busAppointment.getId().equals(statement.getAppointmentId())) {
//                throw new RuntimeException("已生成过结算单 请勿重新生成");
//            }
//        }
//        if (!BusAppointment.STATUS_ARRIVED.equals(busAppointment.getStatus())) {
//            throw new RuntimeException("当前状态无法生成结算单");
//        }
//        busStatement.setCustomerName(busAppointment.getCustomerName());
//        busStatement.setCustomerPhone(busAppointment.getCustomerPhone());
//        busStatement.setActualArrivalTime(busAppointment.getActualArrivalTime());
//        busStatement.setLicensePlate(busAppointment.getLicensePlate());
//        busStatement.setCarSeries(busAppointment.getCarSeries());
//        busStatement.setServiceType(busAppointment.getServiceType());
//        busStatement.setAppointmentId(busAppointment.getId());
//        busStatement.setStatus(BusStatement.STATUS_CONSUME);
//        busStatement.setIsDelete(BusStatement.IS_NOT_DELETE);
//        busStatement.setCreateTime(new Date());
//        return busStatementMapper.insertBusStatement(busStatement);
//    }

    @Override
    public void updateItem(Long statementId, BigDecimal totalAmount, BigDecimal totalQuality, BigDecimal disCount) {
        busStatementMapper.updateItem(statementId,totalAmount,totalQuality,disCount);
    }

    @Override
    public int updateBusPay(Long statementId, Long payId, Integer statusPaid) {
        return busStatementMapper.updateBusPay(statementId,payId,BusStatement.STATUS_PAID);
    }

    @Override
    @Transactional
    public Long createStatement(Long id) {
        if (id==null){
            throw new RuntimeException("参数异常");
        }
        BusAppointment busAppointment = appointmentService.selectBusAppointmentById(id);
        if (busAppointment==null){
            throw new RuntimeException("参数异常");
        }
        BusStatement busStatement = busStatementMapper.selectBusAppointId(id);
        if (busStatement!=null){
            if (!(BusAppointment.STATUS_SETTLED.equals(busAppointment.getStatus())||
            BusAppointment.STATUS_PAID.equals(busAppointment.getStatus())||
            BusAppointment.STATUS_ARRIVED.equals(busAppointment.getStatus())&&
            BusStatement.IS_DELETE.equals(busStatement.getIsDelete()))){
                throw new RuntimeException("状态异常");
            }
        }else {
            if (!BusAppointment.STATUS_ARRIVED.equals(busAppointment.getStatus())){
                throw new RuntimeException("状态异常");
            }
            busStatement = new BusStatement();
            busStatement.setCustomerName(busAppointment.getCustomerName());
            busStatement.setCustomerPhone(busAppointment.getCustomerPhone());
            busStatement.setActualArrivalTime(busAppointment.getActualArrivalTime());
            busStatement.setLicensePlate(busAppointment.getLicensePlate());
            busStatement.setCarSeries(busAppointment.getCarSeries());
            busStatement.setServiceType(busAppointment.getServiceType());
            busStatement.setAppointmentId(id);
            busStatement.setStatus(BusStatement.STATUS_CONSUME);
            busStatement.setDiscountAmount(new BigDecimal("0.0"));
            busStatement.setCreateTime(new Date());
            busStatement.setIsDelete(BusStatement.IS_NOT_DELETE);
            busStatementMapper.insertBusStatement(busStatement);
            appointmentService.updateStatus(BusAppointment.STATUS_SETTLED,id);
        }
        if (BusStatement.IS_DELETE.equals(busStatement.getIsDelete())){
            busStatementMapper.deleteBusStatementByIds(busStatement.getId(), BusStatement.IS_NOT_DELETE);
            appointmentService.updateStatus(BusAppointment.STATUS_SETTLED,id);
        }
        return busStatement.getId();
    }

    @Override
    /**
     * 更新巴士单据信息
     * @param busStatement 包含更新信息的巴士单据对象
     * @return 更新成功返回1，失败抛出异常
     * @throws RuntimeException 当参数为空、参数不完整、格式不正确、数据不存在或状态不允许时抛出异常
     */
    public int updateBusStatement(BusStatement busStatement) {
        // 检查参数是否为空
        if (busStatement==null) {
            throw new RuntimeException("参数异常");
        }
        // 检查必要字段是否为空
        if (busStatement.getCustomerName()==null
                || busStatement.getLicensePlate()==null
                || busStatement.getActualArrivalTime()==null
                || busStatement.getServiceType()==null
                || busStatement.getCarSeries()==null
                || busStatement.getCustomerPhone()==null) {
            throw new RuntimeException("参数异常");
        }
        // 验证手机号格式
        if (!RegexUtils.isPhoneLegal(busStatement.getCustomerPhone())) {
            throw new RuntimeException("手机号格式不正确");
        }
        // 验证车牌号格式
        if (VehiclePlateNoUtil.getVehiclePlateNo(busStatement.getLicensePlate())==null) {
            throw new RuntimeException("车牌号格式不正确");
        }
        // 获取当前时间并增加1分钟，用于验证到店时间
        Date updateNow = DateUtil.changeDate(new Date(), Calendar.MINUTE, 1);
        // 检查到店时间是否早于当前时间
        if (updateNow.before(busStatement.getActualArrivalTime())) {
            throw new RuntimeException("到店时间需要早于当前时间");
        }
        // 根据ID查询原单据信息
        BusStatement oldObj = this.selectBusStatementById(busStatement.getId());
        // 检查单据是否存在
        if (oldObj==null ||oldObj.getStatus()==null || oldObj.getIsDelete()== null) {
            throw new RuntimeException("数据不存在");
        }
        if (!oldObj.getStatus().equals(busStatement.getStatus())||!oldObj.getIsDelete().equals(busStatement.getIsDelete())) {
            throw new RuntimeException("非法参数");
        }
        // 检查单据状态是否允许编辑
        if (!BusStatement.STATUS_CONSUME.equals(oldObj.getStatus())) {
            throw new RuntimeException("只有在消费中才可以进行编辑操作");
        }
        if (BusStatement.IS_DELETE.equals(oldObj.getIsDelete())) {
            throw new RuntimeException("只有在未删除才可以进行编辑操作");
        }
        // 执行更新操作并返回结果
        return busStatementMapper.updateBusStatement(busStatement);
    }

    @Override
    @Transactional
    public int deleteBusStatementByIds(Long id) {
        if (id==null){
            throw new RuntimeException("id不能为空");
        }
        BusStatement busStatement = this.selectBusStatementById(id);
        if (BusStatement.IS_DELETE.equals(busStatement.getIsDelete())){
            throw new RuntimeException("数据已删除");
        }
        if (busStatement==null || busStatement.getStatus()==null){
            throw new RuntimeException("数据不存在");
        }
        if(!BusStatement.STATUS_CONSUME.equals(busStatement.getStatus())){
            throw new RuntimeException("只有在消费中才可以进行删除操作");
        }
        if (busStatement.getAppointmentId()!=null){
            BusAppointment busAppointment = appointmentService.selectBusAppointmentById(busStatement.getAppointmentId());
            if (busAppointment==null){
                throw new RuntimeException("数据不存在");
            }
            if (BusAppointment.STATUS_PAID.equals(busAppointment.getStatus())){
                throw new RuntimeException("只有在未支付才可以进行删除操作");
            }
            appointmentService.updateStatus(BusAppointment.STATUS_ARRIVED,busAppointment.getId());
        }
        return busStatementMapper.deleteBusStatementByIds(id,BusStatement.IS_DELETE);
    }


}
